from fastapi import APIRouter, status, HTTPException, Depends
from sqlalchemy.orm import Session
import uuid 
import asyncio 
from typing import Dict, Any
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor

from schemas.agent import ChatRequest, CheckRequest, AgentCheckResponse, AgentChatResponse
from core import check_agent as check_agent_core
from db.session import get_db
from log import log_error

# In-memory storage for conversation context
# Maps conversation_id (UUID) to conversation shared context
# In a production environment, this should be replaced with a persistent store like Redis
conversation_store: Dict[str, Dict[str, Any]] = {}

# 配置线程池，设置最大线程数为15
# 这个线程池将被 asyncio.to_thread() 使用
thread_pool = ThreadPoolExecutor(max_workers=15, thread_name_prefix="agent-worker")

# 设置 asyncio 的默认线程池
def set_thread_pool():
    loop = asyncio.get_event_loop()
    loop.set_default_executor(thread_pool)

# 在模块加载时设置线程池
try:
    set_thread_pool()
except RuntimeError:
    # 如果没有运行的事件循环，稍后会在路由中设置
    pass

router = APIRouter(
    prefix="/agent",
    tags=["agent"],
    responses={
        500: {"description": "Internal server error"},
        400: {"description": "Bad request"},
        404: {"description": "Conversation not found"}
    },
)


@router.post("/conversations")
async def create_conversation():
    """
    Create a new conversation and return its ID.
    
    Returns:
        Dictionary with the new conversation_id
    """
    # Generate a new UUID for this conversation
    conversation_id = str(uuid.uuid4())
    
    # Initialize an empty conversation context
    conversation_store[conversation_id] = {
        "conversation_history": [],
        "created_at": str(datetime.now())
    }
    
    return {"conversation_id": conversation_id}


@router.post("/conversations/{conversation_id}/chat", response_model=AgentChatResponse, status_code=status.HTTP_200_OK)
async def chat(conversation_id: str, request: ChatRequest) -> AgentChatResponse:
    """
    Handle chat (free conversation) with the agent.
    
    Args:
        conversation_id: UUID for the conversation to maintain context
        request: Chat request containing user input
        
    Returns:
        Agent response with result
    """
    # Validate UUID format
    try:
        uuid.UUID(conversation_id)
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid conversation ID format. Must be a valid UUID."
        )
    
    # Check if conversation exists
    if conversation_id not in conversation_store:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Conversation with ID {conversation_id} not found"
        )
    
    # Get conversation history from store
    conversation_history = conversation_store[conversation_id].get("conversation_history", [])
    
    # Process chat request
    result, shared = await check_agent_core.handle_chat(
        user_input=request.user_input,
        conversation_history=conversation_history
    )
    
    # Update conversation store with latest context
    conversation_store[conversation_id] = shared
    
    return AgentChatResponse(result=result)


@router.get("/conversations")
async def list_conversations():
    """
    List all active conversations.
    
    Returns:
        List of conversation IDs and their creation timestamps
    """
    return [
        {"conversation_id": cid, "created_at": data.get("created_at")}
        for cid, data in conversation_store.items()
    ]


@router.delete("/conversations/{conversation_id}")
async def delete_conversation(conversation_id: str):
    """
    Delete a conversation by ID.
    
    Args:
        conversation_id: UUID of the conversation to delete
        
    Returns:
        Success message
        
    Raises:
        HTTPException: If conversation not found
    """
    # Validate UUID format
    try:
        uuid_obj = uuid.UUID(conversation_id)
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid conversation ID format. Must be a valid UUID."
        )
    
    # Check if conversation exists
    if conversation_id not in conversation_store:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Conversation with ID {conversation_id} not found"
        )
    
    # Delete the conversation
    del conversation_store[conversation_id]
    
    return {"message": f"Conversation {conversation_id} deleted successfully"}


@router.post("/check", response_model=list[AgentCheckResponse], status_code=status.HTTP_200_OK)
async def check(
    requests: list[CheckRequest],
    db: Session = Depends(get_db)
):
    """
    批量问题检查接口。

    接收 CheckRequest 列表，分别调用大模型进行检查，并保证返回结果顺序与输入一致。
    """
    # 确保线程池已设置
    try:
        set_thread_pool()
    except RuntimeError:
        pass  # 线程池可能已经设置
    
    try:
        return await check_agent_core.batch_check_requests(requests)
    except Exception as e:
        log_error(f"批量问题检查失败: {str(e)}", module="agent.check")
        raise HTTPException(status_code=500, detail="批量问题检查失败")
